import { defineStore } from 'pinia';
import Cookies from 'js-cookie';

export const useAppStore = defineStore('app', {
  state: () => ({
    sidebar: {
      opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
      withoutAnimation: false
    },
    device: 'desktop',
    size: Cookies.get('size') || 'medium',
    layoutSettings: {
      primaryColor: localStorage.getItem('primaryColor') || '#1677ff',
      darkMode: localStorage.getItem('darkMode') === 'true' || false,
      navMode: localStorage.getItem('navMode') || 'side', // side, top, mix, column, drawer
      theme: localStorage.getItem('theme') || 'light',
      layout: localStorage.getItem('layout') || 'mix',
      contentWidth: localStorage.getItem('contentWidth') || 'fluid',
      fixedHeader: localStorage.getItem('fixedHeader') !== 'false',
      fixedSidebar: localStorage.getItem('fixedSidebar') !== 'false',
      splitMenus: localStorage.getItem('splitMenus') === 'true' || false,
      colorWeak: localStorage.getItem('colorWeak') === 'true' || false,
      multiTab: localStorage.getItem('multiTab') !== 'false',
      hideFooter: localStorage.getItem('hideFooter') === 'true' || false,
      tableStriped: localStorage.getItem('tableStriped') === 'true' || false,
      tableShowHeader: localStorage.getItem('tableShowHeader') !== 'false'
    },
    // 系统配置
    systemConfig: {
      title: localStorage.getItem('systemTitle') || 'BearJia Admin',
      logo: localStorage.getItem('systemLogo') || '/src/assets/images/logo.png',
      copyright: localStorage.getItem('systemCopyright') || 'Copyright © 2024 BearJia',
      version: localStorage.getItem('systemVersion') || '1.0.0',
      description: localStorage.getItem('systemDescription') || 'BearJia后台管理系统',
      keywords: localStorage.getItem('systemKeywords') || 'BearJia,Admin,Vue3,Ant Design Vue'
    }
  }),

  actions: {
    toggleSideBar() {
      this.sidebar.opened = !this.sidebar.opened;
      this.sidebar.withoutAnimation = false;
      if (this.sidebar.opened) {
        Cookies.set('sidebarStatus', 1);
      } else {
        Cookies.set('sidebarStatus', 0);
      }
    },

    closeSideBar(withoutAnimation) {
      Cookies.set('sidebarStatus', 0);
      this.sidebar.opened = false;
      this.sidebar.withoutAnimation = withoutAnimation;
    },

    toggleDevice(device) {
      this.device = device;
    },

    setSize(size) {
      this.size = size;
      Cookies.set('size', size);
    },

    updateSettings(settings) {
      this.layoutSettings = {
        ...this.layoutSettings,
        ...settings
      };

      // 持久化存储每个设置项
      Object.keys(settings).forEach(key => {
        localStorage.setItem(key, String(settings[key]));
      });

      // 应用主题变化
      this.applyTheme();
    },

    // 更新系统配置
    updateSystemConfig(config) {
      this.systemConfig = { ...this.systemConfig, ...config };

      // 持久化存储系统配置
      Object.keys(config).forEach(key => {
        localStorage.setItem(`system${key.charAt(0).toUpperCase() + key.slice(1)}`, config[key]);
      });

      // 更新页面标题
      if (config.title) {
        document.title = config.title;
      }
    },

    // 应用主题
    applyTheme() {
      try {
        const root = document.documentElement;

        // 设置主题色（动态变化的部分）
        root.style.setProperty('--primary-color', this.layoutSettings.primaryColor);
        root.style.setProperty('--ant-primary-color', this.layoutSettings.primaryColor);

        // 计算主题色的变体
        const primaryColor = this.layoutSettings.primaryColor;
        const primaryColorHover = `color-mix(in srgb, ${primaryColor} 90%, white)`;
        const primaryColorActive = `color-mix(in srgb, ${primaryColor} 110%, black)`;
        const primary1 = `color-mix(in srgb, ${primaryColor} 20%, white)`;

        root.style.setProperty('--ant-primary-color-hover', primaryColorHover);
        root.style.setProperty('--ant-primary-color-active', primaryColorActive);
        root.style.setProperty('--ant-primary-1', primary1);
        
        root.style.setProperty('--primary-color-hover', primaryColorHover);
        root.style.setProperty('--primary-color-active', primaryColorActive);
        root.style.setProperty('--primary-1', primary1);

        // 设置暗色主题类名（让CSS变量自动生效）
        if (this.layoutSettings.darkMode) {
          root.classList.add('dark-theme');
          document.body.classList.add('dark-theme');
        } else {
          root.classList.remove('dark-theme');
          document.body.classList.remove('dark-theme');
        }

        // 设置色弱模式
        if (this.layoutSettings.colorWeak) {
          root.classList.add('color-weak');
        } else {
          root.classList.remove('color-weak');
        }

        console.log('✅ 主题应用成功:', this.layoutSettings);
      } catch (error) {
        console.error('❌ 主题应用失败:', error);
      }
    },

    // 重置所有设置
    resetSettings() {
      const defaultSettings = {
        primaryColor: '#1677ff',
        darkMode: false,
        navMode: 'side',
        theme: 'light',
        layout: 'mix',
        contentWidth: 'fluid',
        fixedHeader: true,
        fixedSidebar: true,
        splitMenus: false,
        colorWeak: false,
        multiTab: true,
        hideFooter: false,
        tableStriped: false,
        tableShowHeader: true
      };

      this.layoutSettings = defaultSettings;

      // 清除localStorage
      Object.keys(defaultSettings).forEach(key => {
        localStorage.removeItem(key);
      });

      this.applyTheme();
    },

    // 导出配置
    exportSettings() {
      const config = {
        layoutSettings: this.layoutSettings,
        systemConfig: this.systemConfig,
        timestamp: new Date().toISOString()
      };

      const blob = new Blob([JSON.stringify(config, null, 2)], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `bearjia-config-${new Date().toISOString().split('T')[0]}.json`;
      a.click();
      URL.revokeObjectURL(url);
    },

    // 导入配置
    importSettings(config) {
      if (config.layoutSettings) {
        this.updateSettings(config.layoutSettings);
      }
      if (config.systemConfig) {
        this.updateSystemConfig(config.systemConfig);
      }
    }
  }
});